import './index.scss'
import dayjs from 'dayjs'
import { useRequest } from 'alova/client'
import { useNavigate } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { useEventEmitter, useMount, useSize, useRafInterval } from 'ahooks'
import { Tooltip, Select, DatePicker, Input, Button, Spin, Result } from "antd"

import { Http } from '../API'
import { imageUrl } from '../Config/config'
import { GetIndexedDB } from '../Utils/IndexedDB'
import { VChartTemplate } from '../Utils/VCharts'
import { ParamsMapping } from '../Config/VChartsConfig'

import {
    LogoutOutlined,
    FieldTimeOutlined,
    ConsoleSqlOutlined,
    ContainerOutlined,
    BarChartOutlined
} from '@ant-design/icons'

import { ModelBox } from '../Model'

const { RangePicker } = DatePicker
const HomeA01List = [
    { uuid: 1, title: '总金额', value: 'totalMoney', unit: '万元', img: '总金额.png', type: 1 },
    { uuid: 2, title: '已对账', value: 'settleMoney', unit: '万元', img: '已结.png', type: 1 },
    { uuid: 3, title: '未对账', value: 'outstandingMoney', unit: '万元', img: '未结.png', type: 1 },
    { uuid: 4, title: '承运单位', value: 'carrierCount', unit: '个', img: '承运.png', type: 2 },
    { uuid: 5, title: '累计进场', value: 'accumulativeCar', unit: '台', img: '累计.png', type: 2 },
    { uuid: 6, title: '当前在场', value: 'nowCar', unit: '台', img: '当前.png', type: 2 },
]

const feiYongType = [{ uuid: '运费', label: '运费' }, { uuid: '材料费', label: '材料费' }, { uuid: '运费和材料费', label: '运费和材料费' }]

const DataMapping = [{ value: 1, label: "按日" }, { value: 0, label: "按月" }]

const StartIndex = () => {
    const onNavigate = useNavigate()
    const ItemBox = useRef()
    const size = useSize(ItemBox)
    const [Style, setStyle] = useState()
    const [orgInfo, setOrgInfo] = useState([])
    const [Page, setPage] = useState('Home')
    const [DateType, setDataType] = useState(1)
    const onSwitch = () => setPage(e => e === 'Home' ? 'Item' : 'Home')
    const [pguid, setPguid] = useState()
    const [Options, setOptions] = useState({})
    const [Params, setParams] = useState({
        YS_CaiLiaoName: undefined,
        YS_FaLiaoYuan: undefined,
        YS_ShouLiaoYuan: undefined,
        YS_YunShuFang: undefined,
        SupplierName: undefined,
        FeiYongType: undefined,
        YS_CheHao: undefined,
    })
    const [DefaultList, setDefaultList] = useState([])
    const [DefaultSpin, setDefaultSpin] = useState(false)
    const [OptionsCall, setOptionsCall] = useState()
    const onResetFunc = () => {
        setParams({
            YS_CaiLiaoName: undefined,
            YS_FaLiaoYuan: undefined,
            YS_ShouLiaoYuan: undefined,
            YS_YunShuFang: undefined,
            SupplierName: undefined,
            FeiYongType: undefined,
            YS_CheHao: undefined,
        })
    }
    const [DateSelect, setDataSelect] = useState([dayjs().add(-2, 'day'), dayjs()])
    useMount(async () => {
        const { orgInfo } = await GetIndexedDB('options')
        setPguid(orgInfo[0].uuid)
        setOrgInfo(orgInfo)
    })
    const onAmdin = () => onNavigate('/Admin')
    const onSignOut = () => onNavigate('/')

    const [Open, setOpen] = useState(false)
    const [Date, setDate] = useState(5)
    const onTiming = () => {
        setOptionsCall({ type: 'Timing', title: '定时设置', width: 600, data: { Open, Date } })
        setDate(1000)
    }

    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'setTiming') {
            setOpen(data.Open)
            setDate(data.Date)
        }
    })

    const BtnMapping = [
        { uuid: 2, title: '定时刷新', icon: <FieldTimeOutlined onClick={onTiming} /> },
        { uuid: 3, title: '跳转后台', icon: <ConsoleSqlOutlined onClick={onAmdin} /> },
        { uuid: 4, title: '退出登录', icon: <LogoutOutlined onClick={onSignOut} />, className: 'out' },
    ]

    const { send: getHome } = useRequest(params => Http({ url: 'getDaPingInfo', params }), { immediate: false })
    const { send: getOption } = useRequest(params => Http({ url: 'getCiaoLiaoTypeInfoV2', params }), { immediate: false })
    const { send: getDetails } = useRequest(params => Http({ url: 'getCaiLiaoYunShuInfo', params }), { immediate: false })
    const [HomeA01, setHomeA01] = useState({ totalMoney: 0, settleMoney: 0, outstandingMoney: 0, carrierCount: 0, accumulativeCar: 0, nowCar: 0 })
    const [HomeA03, setHomeA03] = useState()
    const [HomeA04, setHomeA04] = useState()
    const [HomeA05, setHomeA05] = useState()
    const [HomeA06, setHomeA06] = useState()
    const [HomeA07, setHomeA07] = useState()
    const [HomeA08, setHomeA08] = useState()
    const [HomeA09, setHomeA09] = useState()

    const getHomeApi = () => {
        const [start, end] = DateSelect
        const begindate = dayjs(start).format('YYYY-MM-DD')
        const enddate = dayjs(end).format('YYYY-MM-DD')
        getHome({ pguid, orgtype: 1, statisticstype: DateType, begindate, enddate }).then(res => {
            const { list, list1, list2, list3, list4, list5, list6, list7 } = res
            const { api, params, colorPalette, xField, yField, ...common } = ParamsMapping.VChartTemplateA01Common
            const style = {
                ...ParamsMapping.VChartTemplateA01Axes,
                ...ParamsMapping.VChartTemplateA01Legends,
                ...ParamsMapping.VChartTemplateA01Label,
                ...ParamsMapping.VChartTemplateA01Tooltip,
                ...ParamsMapping.VChartTemplateA01Crosshair,
                ...ParamsMapping.VChartTemplateA01Title,
                ...ParamsMapping.VChartTemplateA01Line,
                ...ParamsMapping.VChartTemplateA01Bar,
                ...ParamsMapping.VChartTemplateA01Point,
                ...ParamsMapping.VChartTemplateA01BarBack,
                ...ParamsMapping.VChartTemplateA01LineLabel,
                ...ParamsMapping.VChartTemplateA01TotalLabel,
                ...ParamsMapping.VChartTemplateA01MarkLine,
                ...ParamsMapping.VChartTemplateA01MarkPoint,
                ...ParamsMapping.VChartTemplateA01ScrollBar,
                ...common,
                color: colorPalette.map(item => item.color),
            }

            const A05 = list1.reduce((acc, item) => {
                acc.push(
                    { name: '已对账', type: item.yS_YunShuFang, value: item.settleMoney },
                    { name: '未对账', type: item.yS_YunShuFang, value: item.outstandingMoney }
                )
                return acc
            }, [])
            const A06 = list2.reduce((acc, item) => {
                acc.push(
                    { name: '已对账', type: item.yS_CaiLiaoName, value: item.settleMoney },
                    { name: '未对账', type: item.yS_CaiLiaoName, value: item.outstandingMoney }
                )
                return acc
            }, [])
            const A07 = list6.reduce((acc, item) => {
                acc.push(
                    { name: '已对账', type: item.yS_YunShuFang, value: item.settleMoney },
                    { name: '未对账', type: item.yS_YunShuFang, value: item.outstandingMoney }
                )
                return acc
            }, [])
            const A08 = list7.reduce((acc, item) => {
                acc.push(
                    { name: '已对账', type: item.yS_CaiLiaoName, value: item.settleMoney },
                    { name: '未对账', type: item.yS_CaiLiaoName, value: item.outstandingMoney }
                )
                return acc
            }, [])

            const A09 = list5.reduce((acc, item) => {
                acc.push(
                    { name: '数量', type: item.yS_ShouLiaoDate, value: item.yS_ShouLiaoShuLiang },
                    { name: '百公里', type: item.yS_ShouLiaoDate, value: item.yS_HeJiYunJu },
                    { name: '台次', type: item.yS_ShouLiaoDate, value: item.yS_TaiCi },
                    { name: '运费(万元)', type: item.yS_ShouLiaoDate, value: item.yS_Money },
                    // { name: '材料费(万元)', type: item.yS_ShouLiaoDate, value: item.caiLiaoFeiJinE },
                )
                return acc
            }, [])

            setStyle(style)
            setHomeA01(list[0])
            setHomeA03(list4.map(({ uuid, tranCompany, carCount }) => ({ uuid, type: tranCompany, value: carCount })))
            setHomeA04(list3.map(({ uuid, yS_CaiLiaoName, cL_EUnit, yS_ShouLiaoShuLiang }) => ({ uuid, type: `${yS_CaiLiaoName}(${cL_EUnit})`, value: yS_ShouLiaoShuLiang })))
            setHomeA05(A05)
            setHomeA06(A06)
            setHomeA07(A07)
            setHomeA08(A08)
            setHomeA09(A09)
        })
    }

    const clear = useRafInterval(getHomeApi, Date * 1000);
    useEffect(() => {
        if (Open) setDate(Date)
        else clear()
    }, [Open, Date])

    useEffect(() => {
        if (pguid) {
            getOption({ OrganizationUuid: pguid, DataType: 'statisticsName,faLiaoYuan,shouLiaoYuan,yunShuFang,supplierName,orgInfo' }).then(res => {
                onResetFunc()
                setOptions(res)
                getHomeApi()
            })
        }
    }, [pguid, DateSelect, DateType])

    const ImageTitle = ({ title }) => {
        return (
            <div className='ImageTitle'>
                <div>
                    <img src={imageUrl + '前框.png'} alt="" />
                    <img src={imageUrl + '后框.png'} alt="" />
                </div>
                <div>{title}</div>
            </div>
        )
    }

    const onSearch = () => {
        setDefaultSpin(true)
        const [start, end] = DateSelect
        const begindate = dayjs(start).format('YYYY-MM-DD')
        const enddate = dayjs(end).format('YYYY-MM-DD')
        const params = { pageIndex: 1, pageSize: 100000, pguid, begindate, enddate, ...Params }
        getDetails(params).then(res => {
            setDefaultSpin(false)
            setDefaultList(res.list)
        })
    }

    const ItemTop = [
        { title: '承运单位', flex: 300, value: 'yS_YunShuFang' },
        { title: '供应商', flex: 200, value: 'supplierName' },
        { title: '车牌号码', flex: 150, value: 'yS_CheHao' },
        { title: '材料名称', flex: 200, value: 'yS_CaiLiaoName' },
        { title: '单位', flex: 120, value: 'cL_EUnit' },
        { title: '运距（公里）', flex: 150, value: 'yS_HeJiYunJu' },
        { title: '收料数量', flex: 120, value: 'yS_ShouLiaoShuLiang' },
        { title: '运费单价（元）', flex: 180, value: 'yS_Price' },
        { title: '运费（元）', flex: 120, value: 'yS_Money' },
        { title: '材料费单价（元）', flex: 200, value: 'caiLiaoFeiDanJia' },
        { title: '材料费（元）', flex: 200, value: 'caiLiaoFeiJinE', },
        { title: '合计金额 (运费+材料费)', flex: 300, value: 'totalAmount' },
        { title: '发料时间', flex: 220, value: 'yS_FaLiaoDate' },
        { title: '收料时间', flex: 220, value: 'yS_ShouLiaoDate' },
        { title: '发料地', flex: 160, value: 'yS_FaLiaoDi' },
        { title: '收料地', flex: 160, value: 'yS_ShouLiaoDi' },
        { title: '发料员', flex: 120, value: 'yS_FaLiaoYuan' },
        { title: '收料员', flex: 120, value: 'yS_ShouLiaoYuan' },
        { title: '费用类型', flex: 120, value: 'feiYongType' },
        { title: '数据明细', flex: 240, value: 'yS_ShuJuLeiXing' },
    ]

    const onAnnex = (item) => {
        setOptionsCall({
            type: 'AnnexImageList',
            title: '附件信息',
            data: {
                btnData: {
                    url: 'getYunShuImage',
                    parameters: [{ file: 'CaiLiaoYunShuUuid', value: 'yS_Gid' }],
                    success: { file: 'data', url: 'webURL', name: 'imageCategory' }
                },
                record: item
            }
        })
    }

    return (
        <div className='StartIndex'>
            <img className='PageBack' src={imageUrl + '背景图.png'} alt="" />
            <div className='TopNav'>
                <img className='NavImage' src={imageUrl + '顶栏背景.png'} alt="" />
                <div className='Title'>材料运输管理平台</div>
                <div className='Search'>
                    <Select value={DateType} options={DataMapping} onChange={setDataType} />
                    <RangePicker picker={DateType === 1 ? 'date' : 'month'} allowClear={false} value={DateSelect} onChange={setDataSelect} />
                    <Select placeholder='请选择项目' fieldNames={{ value: 'uuid' }} value={pguid} options={orgInfo} onChange={setPguid} />
                </div>
                <div className='Options'>
                    <Tooltip title={Page === 'Home' ? '数据分析' : '数据统计'}>
                        <div className='Btn' onClick={onSwitch} >
                            {Page === 'Home' ? <ContainerOutlined /> : <BarChartOutlined />}
                        </div>
                    </Tooltip>
                    {BtnMapping.map(({ uuid, title, icon, className }) =>
                        <Tooltip key={uuid} title={title}  >
                            <div className={`Btn ${className}`} >
                                {icon}
                            </div>
                        </Tooltip>
                    )}
                </div>
            </div>
            <div className='Outlet'>
                <div className={`Home animate__animated ${Page === 'Home' ? 'animate__fadeInUp' : 'animate__fadeOutDown'}`}>
                    <div className='HomeA01'>
                        <div>
                            <ImageTitle title='运输情况' />
                            <div className='List'>
                                {HomeA01List.map(({ uuid, title, value, unit, img, type }) =>
                                    <div key={uuid} className={type === 1 ? 'A01' : 'A02'}>
                                        <img src={imageUrl + img} alt="" />
                                        <div>{title}</div>
                                        <div>{HomeA01[value]}</div>
                                        <div>{unit}</div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                    <div className='HomeA03'>
                        <div>
                            <ImageTitle title='承运单位运费汇总' />
                            <div className='Charts'>
                                {Style && HomeA05 && <VChartTemplate data={HomeA05} style={Style} vType='HomeA05' />}
                            </div>
                        </div>
                        <div>
                            <ImageTitle title='材料运费汇总' />
                            <div className='Charts'>
                                {Style && HomeA07 && <VChartTemplate data={HomeA07} style={Style} vType='HomeA07' />}
                            </div>
                        </div>
                    </div>

                    <div className='HomeA03'>
                        <div>
                            <ImageTitle title='机械进场情况' />
                            <div className='Charts' >
                                {Style && HomeA03 && <VChartTemplate data={HomeA03} style={Style} vType='HomeA03' />}
                            </div>
                        </div>
                        <div>
                            <ImageTitle title='材料运输情况' />
                            <div className='Charts'>
                                {Style && HomeA04 && <VChartTemplate data={HomeA04} style={Style} vType='HomeA04' />}
                            </div>
                        </div>
                    </div>
                    <div className='HomeA03'>
                        <div>
                            <ImageTitle title='供应商材料费汇' />
                            <div className='Charts'>
                                {Style && HomeA06 && <VChartTemplate data={HomeA06} style={Style} vType='HomeA06' />}
                            </div>
                        </div>
                        <div>
                            <ImageTitle title='材料费汇总' />
                            <div className='Charts'>
                                {Style && HomeA08 && <VChartTemplate data={HomeA08} style={Style} vType='HomeA08' />}
                            </div>
                        </div>
                    </div>
                    <div className='HomeA04'>
                        <ImageTitle title='运输统计' />
                        <div className='Charts'>
                            {Style && HomeA09 && <VChartTemplate data={HomeA09} style={Style} vType='HomeA09' />}
                        </div>
                    </div>
                </div>
                <div className={`Item animate__animated ${Page === 'Home' ? 'animate__fadeOutDown' : 'animate__fadeInUp'}`}>
                    <ImageTitle title='数据分析' />
                    <div className='ItemSearch'>
                        <div>
                            <Select
                                allowClear
                                placeholder='选择材料名称'
                                fieldNames={{ value: 'uuid' }}
                                options={Options.statisticsName}
                                value={Params.YS_CaiLiaoName}
                                onChange={e => setParams(data => ({ ...data, YS_CaiLiaoName: e }))}
                            />
                            <Select
                                allowClear
                                placeholder='选择承运单位'
                                fieldNames={{ value: 'uuid' }}
                                options={Options.yunShuFang}
                                value={Params.YS_YunShuFang}
                                onChange={e => setParams(data => ({ ...data, YS_YunShuFang: e }))}
                            />
                            <Select
                                allowClear
                                placeholder='选择发料员'
                                fieldNames={{ value: 'uuid' }}
                                options={Options.faLiaoYuan}
                                value={Params.YS_FaLiaoYuan}
                                onChange={e => setParams(data => ({ ...data, YS_FaLiaoYuan: e }))}
                            />
                            <Select
                                allowClear
                                placeholder='选择收料员'
                                fieldNames={{ value: 'uuid' }}
                                options={Options.shouLiaoYuan}
                                value={Params.YS_ShouLiaoYuan}
                                onChange={e => setParams(data => ({ ...data, YS_ShouLiaoYuan: e }))}
                            />
                            <Select
                                allowClear
                                placeholder='选择供应商'
                                fieldNames={{ value: 'uuid' }}
                                options={Options.supplierName}
                                value={Params.SupplierName}
                                onChange={e => setParams(data => ({ ...data, SupplierName: e }))}
                            />
                            <Select
                                allowClear
                                placeholder='选择费用类型'
                                fieldNames={{ value: 'uuid' }}
                                options={feiYongType}
                                value={Params.FeiYongType}
                                onChange={e => setParams(data => ({ ...data, FeiYongType: e }))}
                            />
                            <Input placeholder='输入车牌号' value={Params.YS_CheHao} />
                        </div>
                        <div>
                            <Button type='primary' onClick={onSearch}>搜索</Button>
                            <Button type='primary' ghost onClick={() => {
                                onResetFunc()

                            }}>重置</Button>
                        </div>
                    </div>
                    <div className='ItemContent' ref={ItemBox}>
                        <div className='ItemScroll'>
                            <div className='ItemTop'>
                                {ItemTop.map(({ title, flex }, index) =>
                                    <div key={index} style={{ flex }}>{title}</div>
                                )}
                            </div>
                            {size &&
                                <div className='ItemDefault'>
                                    {DefaultSpin ?
                                        <div className='DefaultTips' style={{ width: size.width, height: size.height - 60 }}>
                                            <Spin size="large" />
                                        </div> :
                                        DefaultList.length === 0 ?
                                            <div className='DefaultTips' style={{ width: size.width, height: size.height - 60 }}>
                                                <Result status="404" title="暂无数据,请尝试切换条件!" />
                                            </div> :
                                            <div className='DefaultData'>
                                                {DefaultList.map((item, index) =>
                                                    <div key={index} onClick={() => onAnnex(item)}>
                                                        {ItemTop.map(({ flex, value }, int) => <div key={int} style={{ flex }}>{item[value]}</div>)}
                                                    </div>
                                                )}
                                            </div>
                                    }
                                </div>
                            }
                        </div>
                    </div>
                </div>
            </div>
            <ModelBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div>
    )
}

export default StartIndex;